package cn.yusei.teamTribe.service.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.yusei.teamTribe.constant.ResponseCode;
import cn.yusei.teamTribe.constant.UsernameType;
import cn.yusei.teamTribe.dao.JedisDAO;
import cn.yusei.teamTribe.dao.user.UserAuthDAO;
import cn.yusei.teamTribe.dao.user.UserDAO;
import cn.yusei.teamTribe.dao.user.po.UserAuthPO;
import cn.yusei.teamTribe.dao.user.po.UserPO;
import cn.yusei.teamTribe.entity.User;
import cn.yusei.teamTribe.util.EncryptionUtil;
import cn.yusei.teamTribe.util.JedisKeyUtil;
import cn.yusei.teamTribe.util.SaltUtil;

@Service
public class UserService {

	@Autowired
	private UserAuthDAO userAuthDAO;
	@Autowired
	private UserDAO userDAO;
	@Autowired
	private JedisDAO jedisDAO;
	
	public int login(User user)
	{
		String username = user.getUsername();
		UserPO userPO = null;
		switch (user.getUsernameType())
		{
			case UsernameType.USERNAME : userPO = userDAO.selectByUsername(username); break;
			case UsernameType.EMAIL : userPO = userDAO.selectByEmail(username); break;
			case UsernameType.PHONE  : userPO = userDAO.selectByPhone(username); break;
		}
		if(userPO == null)
			return ResponseCode.USER_NOT_EXISTS;
		String password = EncryptionUtil.getEncryptedString(user.getPassword() + userPO.getSalt());
		if(!password.equals(userPO.getPassword()))
			return ResponseCode.PASSWORD_ERROR;
		user.setId(userPO.getId());
		return ResponseCode.REQUEST_SUCCESSED;
	}
	
	public int register(User user,String phone, String validateCode)
	{
		String username = user.getUsername();
		if(userDAO.selectByUsername(username) != null)
			return ResponseCode.USER_ALREADY_EXISTS;
//		if(!validateCode.equals(jedisDAO.get(JedisKeyUtil.PHONE_CODE + phone)))
//			return ResponseCode.PHONE_VALIDATECODE_ERROR;
//		jedisDAO.del(JedisKeyUtil.PHONE_CODE + phone);
		String salt = SaltUtil.getSalt();
		String password = EncryptionUtil.getEncryptedString(user.getPassword() + salt);
		UserPO userPO = new UserPO();
		userPO.setUsername(username);
		userPO.setPassword(password);
		userPO.setSalt(salt);
		userDAO.insert(userPO);
		UserPO userPO2 = userDAO.selectByUsername(username);
		UserAuthPO userAuthPO = new UserAuthPO();
		userAuthPO.setId(userPO2.getId());
		userAuthPO.setPhone(phone);
		userAuthDAO.update(userAuthPO);
		return ResponseCode.REQUEST_SUCCESSED;
	}
	
}
